/**
 * @Author: LongTao
 * @program: day04_longtao_springmvc_1917JA_20210108
 * @description: 订单控制层
 * @create: 2021-01-19 21:09
 * @version:1.0
 **/
package com.springmvc.longtao.smbms.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.springmvc.longtao.smbms.pojo.Bill;
import com.springmvc.longtao.smbms.pojo.Provider;
import com.springmvc.longtao.smbms.service.BillService;
import com.springmvc.longtao.smbms.utils.BaseNameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {
    private BillService billService;

    @Autowired
    @Qualifier("billServiceImpl")
    public void setBillService(BillService billService) {
        this.billService = billService;
    }

    /**
     * 查询+分页
     * @param queryProductName
     * @param queryProviderId
     * @param queryIsPayment
     * @param pageNum
     * @param model
     * @return
     */
    @RequestMapping(value = {"/getlist"}, method = RequestMethod.GET)
    public String getList(String queryProductName, Integer queryProviderId, Integer queryIsPayment,Integer pageNum, Model model) {
        /**
         * 第一次进入判断是否空,为空则等于1
         */
      if (pageNum==null){
          pageNum=1;
      }
        Bill bill = new Bill();
        bill.setProductName(queryProductName);
        bill.setProviderId(queryProviderId);
        bill.setIsPayment(queryIsPayment);
        Integer pageSize=2;
        /**
         * 查询订单表
         */
        List<Bill> list = billService.getBillList(bill,pageNum,pageSize);
        PageInfo<Bill> pageInfo=new PageInfo<Bill>(list);
        /**
         * 查询所有的供应商
         */
        List<Provider> providerList = billService.getProviderList();
        System.out.println("providerList = " + providerList);
        /**
         * 获取用户前一次搜索的数据,来传递到下一次页面;
         * 也可使用ajax
         */
        model.addAttribute("queryProductName", queryProductName);
        model.addAttribute("queryProviderId", queryProviderId);
        model.addAttribute("queryIsPayment", queryIsPayment);
        if (pageInfo.getList() != null) {
            model.addAttribute("pageInfo", pageInfo);
            model.addAttribute("providerList", providerList);
        } else {
            model.addAttribute(BaseNameUtils.MESSAGE, "没有任何订单");
        }
        return "billlist";
    }

    /**
     * 跳转去添加页面
     *
     * @return
     */
    @RequestMapping(value = "/goAdd", method = RequestMethod.GET)
    public String goAdd(Model model) {
        //System.out.println("是否成功?");
        List<Provider> providerList = billService.getProviderList();
        model.addAttribute("providerList", providerList);
        return "billadd";
    }

    /**
     * ajax验证billCode是否唯一
     *
     * @param billCode
     * @return
     */
    @RequestMapping("/billCodeVerify")
    @ResponseBody
    public Object billCodeVerify(String billCode) {
        boolean flag = true;
        Bill bill = billService.getBill(billCode);
        if (bill == null) {
            flag = false;
        }
        /**
         * 使用json来传递数据
         */
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("flag", flag);
        String json = JSON.toJSONString(map);
        //  System.out.println("json = " + json);
        return json;
    }

    /**
     * ajax添加用户
     *
     * @param bill
     * @param model
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addBill(Bill bill, Model model, @RequestParam(value = "multipartFile", required = false) MultipartFile multipartFile, HttpServletRequest request) throws IOException {
        System.out.println("multipartFile = " + multipartFile);
        System.out.println("bill = " + bill);
        /**
         * 判断是包含文件上传
         */
        if (!multipartFile.isEmpty()) {
            /**
             * 获取上传文件名字
             */
            String name = multipartFile.getOriginalFilename();
            /**
             * 获取文件内容大小
             */
            long size = multipartFile.getSize();
            /**
             * 判断文件大小是否超过设定的最大值
             */
            if (size > 1048576) {
                model.addAttribute(BaseNameUtils.MESSAGE, "当前系统只能上传约1MB大小的文件");
            }
            /**
             * 防止文件名重名而覆盖
             */

            long rondom = RandomUtils.nextInt(1000000);
            StringBuffer stringBuffer = new StringBuffer(rondom + "_idpatcpath_");
            stringBuffer.append(name);
            System.out.println("stringBuffer = " + stringBuffer);
            /**
             * 获取文件上传路径
             */
            String path = request.getServletContext().getRealPath(File.separator + "statics" + File.separator + "/upload");
            System.out.println("path = " + path);
            StringBuffer _path = new StringBuffer(path);
            _path.append(File.separator + stringBuffer);
            /**
             * 判断是否有该目录,没有则创建
             */
            File file = new File(String.valueOf(_path));
            if (!file.exists()) {
                /**
                 * 没有则递归创建
                 */
                file.mkdirs();
            }
            /**
             * 将文件传输到指定路径
             */
            multipartFile.transferTo(file);
            bill.setIdPicPath(String.valueOf(stringBuffer));
        }

        if (billService.add(bill)) {
            return "redirect:getlist";
        } else {
            return "redirect:goAdd";
        }
    }


    /**
     * 根据billCode来查询详细信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getBillQuery/{id}",method = RequestMethod.GET)
    @ResponseBody
    public Object getBillQuery(@PathVariable String id) {
        Bill bill = new Bill();
        bill = billService.getBillID(id);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("bill", bill);
        String json = JSON.toJSONString(bill);
        System.out.println("json = " + json);
        return json;
    }

    /**
     * 根据id来显示到修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/getUpdateBill/{id}",method = RequestMethod.GET)
    public String getUpdateBill(@PathVariable String id, Model model){
        Bill bill = new Bill();
        bill = billService.getBillID(id);
        List<Provider> list=new ArrayList<Provider>();
        list=billService.getProviderList();
        if(bill!=null){
            model.addAttribute("bill",bill);

        }
        if(list!=null){
            model.addAttribute("proViderList",list);
        }
        return "billmodify";
    }


    /**
     * 根据id修改商品表
     * @param bill
     * @param multipartFile
     * @return
     */
    @RequestMapping(value = "/updateBill",method = RequestMethod.POST)
    public String updateBill(String href, Bill bill, @RequestParam(value = "multipartFile",required = false) MultipartFile multipartFile, HttpServletRequest request, Model model) throws IOException {
      if (!multipartFile.isEmpty()){
          System.out.println("是否正确");
          String _name=multipartFile.getOriginalFilename();
          //获取服务器路径
          String path=request.getServletContext().getRealPath(File.separator+"statics"+File.separator+"upload");
          //获取大小
          long size=multipartFile.getSize();
          //比较大小
          if (size > 1048576) {
              model.addAttribute(BaseNameUtils.MESSAGE, "当前系统只能上传约1MB大小的文件");
          }
          //设置随机数,防止重名
          long rondom=RandomUtils.nextInt(1000000);
          String name=rondom+"_idpatcpath_"+_name;
          path=path+File.separator+name;
          File file=new File(path);
          if (!file.exists()){
              file.mkdirs();
          }
          multipartFile.transferTo(file);
          bill.setIdPicPath(name);
      }
      if (billService.modify(bill)){
          System.out.println("href.substring(26,href.length()-1) = " + href.substring(26, href.length()));
          System.out.println("href = " + href);
          return "redirect:getlist";
      }else{
          return "redirect:getUpdateBill/"+bill.getId();
      }
    }
}